package cn.school.mybatis.controller;

import cn.school.mybatis.pojo.Admin;
import cn.school.mybatis.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/s_login")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @PostMapping("/adminLogin")
    public ModelAndView adminLogin(@ModelAttribute("a") Admin admin, HttpSession session){
        ModelAndView mv=new ModelAndView();
        if (admin.getUsername()!=null&&!admin.getUsername().equals("")&&admin.getPassword()!=null&&!admin.getPassword().equals("")&&adminService.checkAdmin(admin)==true){
            session.setAttribute("USER_LOGIN",admin);
            mv.addObject("userName",admin.getUsername());
            mv.setViewName("school/s_login/welcome");
            return mv;
        }
        mv.setViewName("school/s_login/loginFail");
        return mv;
    }

    @PostMapping("/adminRegister")
    public String adminRegister(@ModelAttribute("a") Admin admin, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        if(admin.getUsername()!=null&&!admin.getUsername().equals("")&&admin.getPassword()!=null&&!admin.getPassword().equals("")&&adminService.checkAdmin(admin)==false){
            if (adminService.add(admin)>0){
                response.getWriter().println("<script>alert('用户注册成功！');</script>");
                return "school/s_login/login";
            }
            response.getWriter().println("<script>alert('用户注册失败！');</script>");
            return "school/s_login/register";
        }
        response.getWriter().println("<script>alert('用户注册失败！已存在的账号！');</script>");
        return "school/s_login/register";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "school/s_login/login";
    }

    @RequestMapping("/toRegister")
    public String toRegister() {
        return "school/s_login/register";
    }
    @RequestMapping("/toLoginOut")
    public String toLoginOut() {
        return "school/s_login/loginOut";
    }

    //局部异常处理：本类产生的异常
    @ExceptionHandler
    public String exceptionHandler(Exception e){
        e.printStackTrace();

        return "error500";
    }

}
